package com.example.module_audio_edit;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.PixelFormat;
import android.media.AudioTrack;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.lifecycle.Observer;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.example.module_audio_edit.base.BaseMvvmActivity;
import com.example.module_audio_edit.base.BaseViewModel;
import com.example.module_audio_edit.dailog.BaseCommonDialog;
import com.fwlst.lib_base.utils.AdUtils;
import com.fwlst.lib_base.utils.BaseUtils;
import com.example.module_audio_edit.Presenter.SoundFilePresenter;
import com.example.module_audio_edit.obj.DialogBox;
import com.example.module_audio_edit.utils.LogU;
import com.example.module_audio_edit.utils.SamplePlayer;
import com.example.module_audio_edit.utils.SongMetadataReader;
import com.example.module_audio_edit.utils.Sound;
import com.example.module_audio_edit.utils.SoundFile;
import com.example.module_audio_edit.view.RangeSeekBar2;
import com.example.module_audio_edit.view.WaveSurfaceView;
import com.example.module_audio_edit.view.WaveformView;
import com.example.module_video_ring.BR;
import com.example.module_video_ring.R;
import com.example.module_video_ring.databinding.ActivityHpAudioEditMainBinding;
import com.hjq.toast.Toaster;
import com.jaygoo.widget.RangeSeekBar.OnRangeChangedListener;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import java.util.Timer;
import java.util.TimerTask;

@Route(path = "/hpVideoRing/route/HpAudioEditMainActivity")
public class HpAudioEditMainActivity extends BaseMvvmActivity<ActivityHpAudioEditMainBinding, BaseViewModel> {
    public SoundFilePresenter presenter;
    public AudioTrack mAudioTrack;
    public Sound sound;
    public ProgressDialog  mProgressDialog,mProgressDialog2;
    public boolean mLoadingKeepGoing;
    private boolean mFinishActivity;
    //==============================
    public String va;
    private SamplePlayer mPlayer;

    private SeekBar seekBar;

    private boolean isJump = true;
    //========================================
    public WaveSurfaceView waveSfv;
    public WaveformView waveView;
    public SoundFile mSoundFile;

    public com.jaygoo.widget.RangeSeekBar seekbar2;
    public RangeSeekBar2 seekbar3;
    private float mMin=0,mMax=100;
    //===============================

    public EditText toed1,toed2;
    public TextView itemtx;
    public Button catere;
    private boolean icon1=false,icon2=false;
    @Override
    protected int initLayout() {
        return R.layout.activity_hp_audio_edit_main;
    }

    @Override
    protected int initBR() {
        return BR.data;
    }

    @Override
    protected void initView() {
        //banner广告
        AdUtils.INSTANCE.loadBannerAd(this,binding.bannerContainer);
        //返回按钮
        binding.returnTb.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPlayer != null) {
                    if (mPlayer.isPlaying() || mPlayer.isPaused()) {
                        mPlayer.stop();
                    }
                    mPlayer.release();
                    timer.cancel();
                    timer.purge();
                    mPlayer = null;
                }
                try {
                    mAudioTrack.pause();  // pause() stops the playback immediately.
                    mAudioTrack.stop();   // Unblock mAudioTrack.write() to avoid deadlocks.
                } catch (Exception e) {
                    // TODO: handle exception
                }
                finish();
            }
        });
        presenter = new SoundFilePresenter(this);
        fid();
        try {
            Bundle bd=this.getIntent().getExtras();
            va = bd.getString("audioFilePath");
            binding.audioName.setText(va.substring(va.lastIndexOf("/")+1));
        }catch (Exception e){
        }
        mPlayer = null;
        presenter.ReadFile2(va);
        binding.button3.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                //onPlay(0);
                onPlay2(0);
            }
        });
        binding.catere.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Catg(1);
            }
        });
        viewModel.getCurrentType().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                if(integer==0) return;
                switch (integer){
                    case 1:
                        if(icon1){
                            binding.icon1BtIv.setImageResource(R.mipmap.module_video_ring_img9);
                        }else {
                            binding.icon1BtIv.setImageResource(R.mipmap.module_video_ring_img9_1);
                        }
                        icon1=!icon1;
                        break;
                    case 2:
                        if(icon2){
                            binding.icon2BtIv.setImageResource(R.mipmap.module_video_ring_img10);
                        }else {
                            binding.icon2BtIv.setImageResource(R.mipmap.module_video_ring_img10_1);
                        }
                        icon2=!icon2;
                        break;
                    case 3:
                        save(2);
                        break;
                    case 4:
                        save(1);
                        break;
                }
            }
        });
    }
    private void save(int type){
        //判断是否选取了区间
        String startTimeText = String.valueOf(binding.toed1.getText());
        String endTimeText = String.valueOf(binding.toed2.getText());
        //没有剪切
        if(startTimeText.equals("00:00") && endTimeText.equals(formatTime(mPlayEndMsec))){
            Log.e("保存的类型", String.valueOf(type));
            if(type==1){
                setSaveDialog(String.valueOf(binding.audioName.getText()));
            }else if(type==2){
                //设置铃声操作
            }
        }else {//有剪切
            Catg(type);
        }
    }
    //保存弹窗
    public void setSaveDialog(String audioName){
        final BaseCommonDialog dialog = new BaseCommonDialog(mContext);
        dialog.setTitle("保存完成").setMessage("文件路径：文件管理/Download/"+audioName)
                .setSingle(true)
                .setNegtive("关闭")
                .setOnClickBottomListener(new BaseCommonDialog.OnClickBottomListener() {
                    @Override
                    public void onPositiveClick() {
                        dialog.dismiss();
                    }
                    @Override
                    public void onNegtiveClick() {
                        dialog.dismiss();
                    }
                }).show();
        dialog.getWindow().setLayout(getScreenWidth(mContext) - 200,
                WindowManager.LayoutParams.WRAP_CONTENT);//设置弹出框宽度为屏幕宽度的三分之二;
    }
    public static int getScreenWidth(Context context){
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
//        int width = dm.widthPixels;         // 屏幕宽度（像素）
//        int height = dm.heightPixels;       // 屏幕高度（像素）
//        float density = dm.density;         // 屏幕密度（0.75 / 1.0 / 1.5）
//        int densityDpi = dm.densityDpi;     // 屏幕密度dpi（120 / 160 / 240）
//        // 屏幕宽度算法:屏幕宽度（像素）/屏幕密度
//        int screenWidth = (int) (width / density);  // 屏幕宽度(dp)
//        int screenHeight = (int) (height / density);// 屏幕高度(dp)
        return dm.widthPixels;
    }
    //设置铃声
    private void Catg(int type) {
        //File file = new File(va);
        //String title2 = file.getName();
        //LogU.i("title2",title2);

        SongMetadataReader metadataReader = new SongMetadataReader(HpAudioEditMainActivity.this, va);
        LogU.i("title2",metadataReader.mTitle);

        double  kdk = (mPlayEndMsec * (mMin/100));//--算出seekbar對區間起始的應百分比

        int frames = waveView.millisecsToPixels((int)kdk);//-取得該相素位置

        double startTime = waveView.pixelsToSeconds(frames);
        int startFrame = waveView.secondsToFrames(startTime);//秒到帧
        LogU.i("1",kdk+"");
        LogU.i("frames",frames+"");
        LogU.i("startTime",startTime+"");
        LogU.i("startFrame",startFrame+"");
        //frames = frames/2;
        double  kdk2 = (mPlayEndMsec * (mMax/100));//--算出seekbar對區間起始的應百分比
        int frames2 = waveView.millisecsToPixels((int)kdk2);//-取得該相素位置

        double endTime = waveView.pixelsToSeconds(frames2);
        int endFrame = waveView.secondsToFrames(endTime);
        //frames2 = frames2/2;
        LogU.i("2",kdk2+"");
        LogU.i("frames2",frames2+"");
        LogU.i("endTime",endTime+"");
        LogU.i("endFrame",endFrame+"");
        int duration = (int)((kdk2 - kdk)/1000 +0.5);
        LogU.i("duration",duration+"");
        presenter.CutReadFile(metadataReader.mTitle+"_2",startFrame,endFrame,duration, mSoundFile,type);
    }



    //-解析完成
    public void Loading(SoundFile mSoundFile) {
        mPlayer = new SamplePlayer(mSoundFile);
        mProgressDialog.setMax(mSoundFile.getFileSizeBytes());//取得最大長度
        this.mSoundFile = mSoundFile;
        mLoadingKeepGoing = true;
        oiruyh();

        //--设置seek
        mPlayEndMsec = waveView.pixelsToMillisecsTotal();
        Log.i("设置seek", "设置seek"+mPlayEndMsec);
        seekBar.setMax(mPlayEndMsec);
        toed1.setText(formatTime(0));
        toed2.setText(formatTime(mPlayEndMsec));
        onPlay2(0);
    }


    private int mPlayStartMsec;
    private int mPlayEndMsec;
    public Handler updateTime= new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                updateDisplay();
            } catch (Exception e) {}
        }
    };

    public Timer timer = new Timer();
    public MyTimerTask timerTask = new MyTimerTask();
    class MyTimerTask extends TimerTask {
        @Override
        public void run() {//这里不能处理UI操作
            Message message = updateTime.obtainMessage(0);
            updateTime.sendMessage(message);
        }
    }


    /**播放音频，@param startPosition 开始播放的时间*/
    private synchronized void onPlay2(int startPosition) {
        if (mPlayer == null)
            return;

        if (mPlayer != null && mPlayer.isPlaying()) {
            mPlayer.pause();
            Log.i("停止一次", "停止一次");
            timer.cancel();
            timer.purge();
            timer = new Timer();
        }

        mPlayEndMsec = waveView.pixelsToMillisecsTotal();
        seekBar.setMax(mPlayEndMsec);

        int kdk = (int)(mPlayEndMsec * (mMin/100));//--算出seekbar對區間起始的應百分比
        Log.i("淦", mMin+"應百分比"+kdk);
        int frames = waveView.millisecsToPixels(kdk);//-取得該相素位置

        mPlayStartMsec = waveView.pixelsToMillisecs(frames);
        Log.i("淦", mPlayStartMsec+"");

        mPlayer.setOnCompletionListener(new SamplePlayer.OnCompletionListener() {
            @Override
            public void onCompletion() {
                handlePause();
                waveView.setPlayback(-1);
                updateDisplay();
                //updateTime.removeMessages(UPDATE_WAV);//将handler对应message queue里的消息清空
                Toast.makeText(getApplicationContext(),"播放完成",Toast.LENGTH_LONG).show();
            }
        });
        mPlayer.seekTo(mPlayStartMsec);
        mPlayer.start();


        timer.schedule(new MyTimerTask(), 10, 5); // 从现在起过0.01秒以后，每隔0.005秒执行一次。

    }



    private synchronized void handlePause(){
        if (mPlayer != null && mPlayer.isPlaying()) {//播放中
            //Log.i("播放中", "播放中");
            mPlayer.pause();
            timer.cancel();
            timer.purge();
            timer = new Timer();
            //updateTime.removeMessages(UPDATE_WAV);
        }
    }
    /**更新upd
     * ateview 中的播放进度*/
    private void updateDisplay() {
        int now = mPlayer.getCurrentPosition();// nullpointer
        //LogU.i("當前PINT", now+""+MyApplication.isInMainThread());
        if (isJump) {
            seekBar.setProgress(now);
            itemtx.setText(formatTime(now));
        }

        int frames = waveView.millisecsToPixels(now);//-取得該相素位置
        waveView.setPlayback(frames);//通过这个更新当前播放的位置

        int kdk = (int)(mPlayEndMsec * (mMax/100));//--算出seekbar對區間起始的應百分比
        //int frames2 = waveView.millisecsToPixels(kdk);//-取得該相素位置
        //int frames3= waveView.pixelsToMillisecs(frames2);


        if (now >= kdk) {
            waveView.setPlayFinish(1);
            if (mPlayer != null && mPlayer.isPlaying()) {
                handlePause();
                mPlayer.seekTo(mPlayStartMsec);
                itemtx.setText(formatTime(mPlayStartMsec));
                LogU.i("OK", "播玩了"+now);
                LogU.i("OK", "播玩了"+kdk);
            }
        }else{
            waveView.setPlayFinish(0);
        }
            /*
            if (now >= mPlayEndMsec ) {
                waveView.setPlayFinish(1);
                if (mPlayer != null && mPlayer.isPlaying()) {
                    mPlayer.pause();
                    //updateTime.removeMessages(UPDATE_WAV);
                    timer.cancel();
                    timer.purge();
                    timer = new Timer();
                    mPlayer.seekTo(0);
                    //seekBar.setProgress(0);
                    LogU.i("當前PINT", now+""+MyApplication.isInMainThread());
                    LogU.i("OK", "播玩了");
                }
            }else{
                waveView.setPlayFinish(0);
            }
            */
        waveView.invalidate();//刷新视图
    }


    public void oiruyh() {
        if (mLoadingKeepGoing) {
            Runnable runnable = new Runnable() {
                public void run() {
                    finishOpeningSoundFile();
                    waveSfv.setVisibility(View.INVISIBLE);
                    waveView.setVisibility(View.VISIBLE);
                }
            };
            this.runOnUiThread(runnable);
        }
    }

    float mDensity;
    /**waveview载入波形完成*/
    private void finishOpeningSoundFile() {
        waveView.setSoundFile(mSoundFile);
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        mDensity = metrics.density;
        waveView.recomputeHeights(mDensity);
    }





    private void fid() {
        waveSfv = (WaveSurfaceView)findViewById(R.id.wavesfv);
        waveView = (WaveformView)findViewById(R.id.waveview);
        seekBar = (SeekBar)findViewById(R.id.sakker);
        seekbar2 = (com.jaygoo.widget.RangeSeekBar)findViewById(R.id.seekbar2);
        seekbar3 = (RangeSeekBar2)findViewById(R.id.bar2);
        toed1 = (EditText)findViewById(R.id.toed1);
        toed2 = (EditText)findViewById(R.id.toed2);
        itemtx = (TextView)findViewById(R.id.itemtx);
        toed1.setKeyListener(null);
        toed2.setKeyListener(null);

        if(waveSfv != null) {
            waveSfv.setLine_off(42);
            //解决surfaceView黑色闪动效果
            waveSfv.setZOrderOnTop(true);
            waveSfv.getHolder().setFormat(PixelFormat.TRANSLUCENT);
        }
        waveView.setLine_offset(42);
        mLoadingKeepGoing = true;
        mFinishActivity = false;
        mProgressDialog  = DialogBox.Prate(this,"");
        mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
                mLoadingKeepGoing = false;
                mFinishActivity = true;
            }
        });
        mProgressDialog2 = DialogBox.Prate2(this,"音频编码裁剪");
        /* */
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //Log.i("操作控制", "摸上時觸發");
                isJump = false;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //Log.i("操作控制", "放開時觸發"+seekBar.getProgress());
                isJump = true;
                //onPlay(seekBar.getProgress());
                if (mPlayer == null)
                    return;

                if (mPlayer != null && mPlayer.isPlaying()) {
                    mPlayer.pause();
                    Log.i("停止一次", "停止一次");
                    timer.cancel();
                    timer.purge();
                    timer = new Timer();
                }
                mPlayer.seekTo(seekBar.getProgress());
                mPlayer.start();

                timer.schedule(new MyTimerTask(), 10, 5); // 从现在起过0.01秒以后，每隔0.005秒执行一次。

            }
        });
        seekbar3.setValue(0, seekbar3.getMax());
        seekbar3.setIstEnable(true);
        seekbar3.setOnRangeChangedListener(new RangeSeekBar2.OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar2 view, float min, float max, boolean isFromUser) {
                //seekbar2.setValue(min, max);
                seekbar2.setLeftProgressDescription((int)min+"%");
                seekbar2.setRightProgressDescription((int)max+"%");
                mMin = min;
                mMax = max;
                int kdk = (int)(mPlayEndMsec * (mMin/100));//--算出seekbar對區間起始的應百分比
                toed1.setText(formatTime(kdk));

                int kdk2 = (int)(mPlayEndMsec * (mMax/100));//--算出seekbar對區間起始的應百分比
                toed2.setText(formatTime(kdk2));
            }
        });
        seekbar2.setValue(0, seekbar2.getMax());
        seekbar2.setOnRangeChangedListener(new OnRangeChangedListener() {
            @Override
            public void onRangeChanged(com.jaygoo.widget.RangeSeekBar view, float min, float max, boolean isFromUser) {
                //Log.i("滑動2", min+"_"+max);
                seekbar3.setValue(min, max);
                seekbar2.setLeftProgressDescription((int)min+"%");
                seekbar2.setRightProgressDescription((int)max+"%");
                mMin = min;
                mMax = max;
                int kdk = (int)(mPlayEndMsec * (mMin/100));//--算出seekbar對區間起始的應百分比
                toed1.setText(formatTime(kdk));

                int kdk2 = (int)(mPlayEndMsec * (mMax/100));//--算出seekbar對區間起始的應百分比
                toed2.setText(formatTime(kdk2));
            }
        });
    }

    //返回监听
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if (mPlayer != null) {
                if (mPlayer.isPlaying() || mPlayer.isPaused()) {
                    mPlayer.stop();
                }
                mPlayer.release();
                timer.cancel();
                timer.purge();
                mPlayer = null;
            }
            try {
                mAudioTrack.pause();  // pause() stops the playback immediately.
                mAudioTrack.stop();   // Unblock mAudioTrack.write() to avoid deadlocks.
            } catch (Exception e) {
                // TODO: handle exception
            }
            finish();
        }
        return false;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPlayer != null) {
            if (mPlayer.isPlaying() || mPlayer.isPaused()) {
                mPlayer.stop();
            }
            mPlayer.release();
            timer.cancel();
            timer.purge();
            mPlayer = null;
        }
        try {
            mAudioTrack.pause();  // pause() stops the playback immediately.
            mAudioTrack.stop();   // Unblock mAudioTrack.write() to avoid deadlocks.
        } catch (Exception e) {
            // TODO: handle exception
        }
        AdUtils.INSTANCE.destroyBannerAd();
    }
    /**
     * 格式化时间，将毫秒转换为分:秒格式
     * @param time
     * @return
     */
    public String formatTime(long time) {
        // TODO Auto-generated method stub
        String min = time / (1000 * 60) + "";
        String sec = time % (1000 * 60) + "";
        if (min.length() < 2) {
            min = "0" + time / (1000 * 60) + "";
        } else {
            min = time / (1000 * 60) + "";
        }
        if (sec.length() == 4) {
            sec = "0" + (time % (1000 * 60)) + "";
        } else if (sec.length() == 3) {
            sec = "00" + (time % (1000 * 60)) + "";
        } else if (sec.length() == 2) {
            sec = "000" + (time % (1000 * 60)) + "";
        } else if (sec.length() == 1) {
            sec = "0000" + (time % (1000 * 60)) + "";
        }
        return min + ":" + sec.trim().substring(0, 2);
    }
    //////////////////////////////////////////////////////測試區////////////////////////////////////////////////////////////////////
    private Thread mPlayThread;
    private boolean mKeepPlaying;
    private int mPlaybackStart; //起始偏移量
    private short[]  mBuffer;

    public void start() {
        Log.i("sound.getmNumSamples()", sound.getmNumSamples()+"");
        mAudioTrack.setNotificationMarkerPosition(sound.getmNumSamples() - 1 - 0);

        mAudioTrack.setPlaybackPositionUpdateListener(
                new AudioTrack.OnPlaybackPositionUpdateListener() {
                    @Override
                    public void onPeriodicNotification(AudioTrack track) {
                        LogU.i("Aud1", "1");
                    }

                    @Override
                    public void onMarkerReached(AudioTrack track) {
                        LogU.i("Aud2", "2");
                    }
                });

        mKeepPlaying = true;
        mAudioTrack.flush();
        mAudioTrack.play();
        mPlayThread = new Thread () {
            public void run() {
                int position = mPlaybackStart * sound.getmChannels();
                sound.getmSamples().position(position);
                int limit = sound.getmNumSamples() * sound.getmChannels();
                Log.i("寫入", "寫入"+limit);
                while (sound.getmSamples().position() < limit && mKeepPlaying) {
                    int numSamplesLeft = limit - sound.getmSamples().position();
                    if(numSamplesLeft >= mBuffer.length) {
                        sound.getmSamples().get(mBuffer);
                    } else {
                        for(int i=numSamplesLeft; i<mBuffer.length; i++) {
                            mBuffer[i] = 0;
                        }
                        sound.getmSamples().get(mBuffer, 0, numSamplesLeft);
                    }
                    //使用以ByteBuffer為參數的寫入方法
                    Log.i("寫入", "寫入");
                    mAudioTrack.write(mBuffer, 0, mBuffer.length);
                }
            }
        };
        mPlayThread.start();
    }

    public void a(AudioTrack mAudioTrack)
    {
        this.mAudioTrack = mAudioTrack;
    }
    public void b(Sound sound, short[]  mBuffer) {
        this.sound = sound;
        this.mBuffer = mBuffer;
    }
    /**
     * 设置来电铃声
     */
    /**
     * WRITE_SETTINGS权限申请
     */
    public void requestWriteSettings(){
        Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //开启一个新activity
        startActivity(intent);
    }
    /**
     * 适配android q以上版本  android 9
     * @param ringtoneFile
     */
    private void setRingtoneAndroidQ(File ringtoneFile){
        Log.d("test","---setRingtoneAndroidQ---");
        String fileType = ringtoneFile.getName().substring(ringtoneFile.getName().lastIndexOf("."));
        ContentValues values = new ContentValues();
        values.put(MediaStore.Audio.Media.DISPLAY_NAME, ringtoneFile.getName());
        values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/"+fileType);
        values.put(MediaStore.Audio.Media.TITLE, ringtoneFile.getName());
        //values.put(MediaStore.Audio.Media.RELATIVE_PATH, "Music/test");
        values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
        values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
        values.put(MediaStore.Audio.Media.IS_ALARM, false);
        values.put(MediaStore.Audio.Media.IS_MUSIC, false);

        /*Uri external = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;//MediaStore.Images.Media.EXTERNAL_CONTENT_URI;


        Uri insertUri = resolver.insert(external, values);*/
        ContentResolver resolver = getContentResolver();
        Uri uri = MediaStore.Audio.Media.getContentUriForPath(ringtoneFile.getAbsolutePath());

        Uri insertUri = this.getContentResolver().insert(uri, values);


        Log.d("test","insertUri: " + insertUri);

        String uriPaht = getFilePathFromContentUri(insertUri,getContentResolver());
        Log.d("test","setRingtoneAndroidQ uriPaht: " + uriPaht);


        OutputStream os = null;
        FileInputStream inputStream = null;

        if(insertUri != null){
            try {
                os = resolver.openOutputStream(insertUri);
                if (os != null) {
                    inputStream = new FileInputStream(ringtoneFile);
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    while ((len=inputStream.read(bytes)) != -1) {
                        os.write(bytes,0,len);
                    }
                    inputStream.close();
                    os.close();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE, insertUri);
        Log.d("test","123 insertUri: " + insertUri);
        Toaster.show("铃声设置完成");
    }
    /**
     *
     * 设置铃声
     *
     * type RingtoneManager.TYPE_RINGTONE 来电铃声
     *             RingtoneManager.TYPE_NOTIFICATION 通知铃声
     *             RingtoneManager.TYPE_ALARM 闹钟铃声
     *
     *  path 下载下来的mp3全路径
     *  title 铃声的名字
     */
    private String getFilePathFromContentUri(Uri selectedVideoUri, ContentResolver contentResolver) {
        String filePath;

        String[] filePathColumn = {MediaStore.MediaColumns.DATA};

        Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);

        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);

        filePath = cursor.getString(columnIndex);

        cursor.close();

        return filePath;

    }
}